<?php

namespace app\http\middleware;

use app\admin\service\NodeService;
use think\Request;

class AuthMiddleware
{

    /**
     * 权限认证入口
     * @param Request  $request
     * @param \Closure $next
     *
     * @return mixed|\think\response\Json
     * @throws \ReflectionException
     */
    public function handle(Request $request, \Closure $next)
    {
        if ($request->module() === 'agency') {
            //代理商
            return $this->__agencyAuth($request, $next);
        } else {
            return $this->__adminAuth($request, $next);
        }
    }


    /**
     * 代理商权限认证
     * @param Request  $request
     * @param \Closure $next
     *
     * @return mixed|\think\response\Json
     * @throws \ReflectionException
     */
    private function __agencyAuth(Request $request, \Closure $next)
    {
        if (\app\agency\service\NodeService::forceAuth()) {
            return $next($request);
        } elseif (\app\agency\service\NodeService::islogin()) {
            return json(['code' => 0, 'msg' => '抱歉，没有访问该操作的权限！']);
        } else {
            return json(['code' => 0, 'msg' => '抱歉，需要登录获取访问权限！', 'url' => url('@agency/login')]);
        }
    }


    /**
     * 总后台权限认证
     * @param Request  $request
     * @param \Closure $next
     *
     * @return mixed|\think\response\Json
     * @throws \ReflectionException
     */
    private function __adminAuth(Request $request, \Closure $next)
    {
        if (NodeService::forceAuth()) {
            return $next($request);
        } elseif (NodeService::islogin()) {
            return json(['code' => 0, 'msg' => '抱歉，没有访问该操作的权限！']);
        } else {
            return json(['code' => 0, 'msg' => '抱歉，需要登录获取访问权限！', 'url' => url('@admin/login')]);
        }
    }









}
